package com.btex.app.treaty;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.btex.app.Config;
import com.btex.app.MyApplication;
import com.btex.app.R;
import com.btex.app.entity.FuturesInfo;
import com.btex.app.entity.FuturesListInfo;
import com.btex.app.pager.BaseFragment;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Tools;
import com.btex.app.treaty.dialog.HistoryDialog;
import com.btex.app.treaty.dialog.LeverSetCounterDialog;
import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/10/26
 * @time 下午11:05
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */


//合约资产

public class QiangPingFragment extends BaseFragment {


    @BindView(R.id.activity_counter_tv_heyue_type)
    TextView mActivityCounterTvHeyueType;
    @BindView(R.id.activity_counter_but_zhang)
    Button mActivityCounterButZhang;
    @BindView(R.id.activity_counter_but_type)
    Button mActivityCounterButType;
    @BindView(R.id.activity_counter_but_long)
    Button mActivityCounterButLong;
    @BindView(R.id.activity_counter_but_short)
    Button mActivityCounterButShort;
    @BindView(R.id.activity_tv_leverage)
    TextView mActivityTvLeverage;
    @BindView(R.id.editText_qiangping_price)
    EditText mEditTextQiangpingPrice;
    @BindView(R.id.editText_qiangpingcang)
    EditText mEditTextQiangpingcang;
    @BindView(R.id.editText_qiangping_number)
    EditText mEditTextQiangpingNumber;
    @BindView(R.id.activity_counter_lin_type)
    LinearLayout mActivityCounterLinType;
    @BindView(R.id.fragment_tv_qiangping_price)
    TextView mFragmentTvQiangpingPrice;
    @BindView(R.id.activity_counter_lin_shouyi)
    LinearLayout mActivityCounterLinShouyi;
    @BindView(R.id.activity_counter_but_sure)
    Button mActivityCounterButSure;
    Unbinder unbinder;
    @BindView(R.id.activity_counter_but_shouyilv)
    Button mActivityCounterButShouyilv;
    @BindView(R.id.activity_counter_but_shouyi)
    Button mActivityCounterButShouyi;
    @BindView(R.id.fragment_lin_type)
    LinearLayout mFragmentLinType;
    @BindView(R.id.fragment_qiangping_number)
    LinearLayout mFragmentQiangpingNumber;
    @BindView(R.id.fragment_qiangping_yu_e)
    LinearLayout mFragmentQiangpingYuE;
    @BindView(R.id.fragment_qiangping_open_price)
    TextView mFragmentQiangpingOpenPrice;
    @BindView(R.id.fragment_qiangping_open_number)
    TextView mFragmentQiangpingOpenNumber;
    @BindView(R.id.fragment_qiangping_open_yu_e)
    TextView mFragmentQiangpingOpenYuE;
    @BindView(R.id.fragment_qiangping_lever)
    LinearLayout mFragmentQiangpingLever;
    private ArrayList<String> mStrings;
    private String mData = "5";
    private String max = "";
    private String type = "1";
    private String mIsreverse = "1";
    private String zhucang = "1";
    private String mQuote_anchor;
    private String mPrice_float_num = "8";
    public boolean isZhang = true;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_qiang_ping_layout, null);

        unbinder = ButterKnife.bind(this, view);
        return view;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mActivityCounterButZhang.setSelected(true);
        mActivityCounterButLong.setSelected(true);
        mActivityCounterButShouyilv.setSelected(true);
        mFragmentQiangpingLever.setVisibility(View.GONE);
        getMxCcontracts("1");

        initListener();

    }

    private void initListener() {


        if (mActivityCounterButShouyi != null) {
            mActivityCounterButShouyi.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mFragmentQiangpingLever.setVisibility(View.VISIBLE);
                    zhucang = "2";
                    setState();
                    mActivityCounterButShouyi.setSelected(true);
                    mFragmentQiangpingYuE.setVisibility(View.GONE);
                    mFragmentQiangpingNumber.setVisibility(View.GONE);
                }
            });

        }

        if (mActivityCounterButShouyilv != null) {
            mActivityCounterButShouyilv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mFragmentQiangpingLever.setVisibility(View.GONE);
                    zhucang = "1";
                    setState();
                    mActivityCounterButShouyilv.setSelected(true);
                    mFragmentQiangpingYuE.setVisibility(View.VISIBLE);
                    mFragmentQiangpingNumber.setVisibility(View.VISIBLE);

                }
            });

        }


        if (mActivityCounterButZhang != null) {
            mActivityCounterButZhang.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    isZhang = true;
                    if (TextUtils.isEmpty(mQuote_anchor)) {
                        mFragmentQiangpingOpenNumber.setText("张");
                    }
                    setButState();
                    mActivityCounterButZhang.setSelected(true);
                }
            });

        }


        if (mActivityCounterButType != null) {
            mActivityCounterButType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    isZhang = false;
                    String trim = mActivityCounterButType.getText().toString().trim();
                    mFragmentQiangpingOpenNumber.setText(trim);

                    setButState();
                    mActivityCounterButType.setSelected(true);
                }
            });

        }


        if (mActivityCounterButLong != null) {
            mActivityCounterButLong.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    type = "1";
                    setButType();
                    mActivityCounterButLong.setSelected(true);

                }
            });

        }


        if (mActivityCounterButShort != null) {
            mActivityCounterButShort.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    type = "-1";
                    setButType();
                    mActivityCounterButShort.setSelected(true);

                }
            });

        }


        if (mActivityCounterButSure != null) {
            mActivityCounterButSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    try {
                        if (mIsreverse.equals("1")) {


                            if (zhucang.equals("1")) {

//                    全仓
                                getQuanCangValue();

                            } else {

//                    逐仓
                                geQiangpingPricetValue();
                            }

                        } else {
//                    逐仓
                            geQiangpingPricetValue();
                        }
                    } catch (Exception e) {
                        mActivityCounterLinShouyi.setVisibility(View.GONE);
                        Toast.makeText(cxt, "数据有误", Toast.LENGTH_SHORT).show();
                    }


                }
            });

        }


        if (mActivityCounterTvHeyueType != null) {
            mActivityCounterTvHeyueType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CounterCorrectActivity activity = (CounterCorrectActivity) getActivity();
                    List<FuturesListInfo.DataBean> data1 = activity.mData1;

                    HistoryDialog historyDialog = new HistoryDialog(getActivity());
                    historyDialog.setData(data1);
                    historyDialog.show();
                    historyDialog.getValue(new HistoryDialog.getValueLIstener() {
                        @Override
                        public void get(String data, String contract_id) {
                            setState();
                            mActivityCounterButZhang.setSelected(true);
                            mActivityCounterButLong.setSelected(true);
                            mActivityCounterButShouyilv.setSelected(true);
                            mFragmentQiangpingYuE.setVisibility(View.VISIBLE);
                            mFragmentQiangpingNumber.setVisibility(View.VISIBLE);

                            mActivityCounterTvHeyueType.setText(data);
                            getMxCcontracts(contract_id);
                        }
                    });
                }
            });

        }


        if (mActivityTvLeverage != null) {
            mActivityTvLeverage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LeverSetCounterDialog leverSetCounterDialog = new LeverSetCounterDialog(getContext());
                    leverSetCounterDialog.setList(mStrings);

                    leverSetCounterDialog.getValue(new LeverSetCounterDialog.getValueLIstener() {


                        @Override
                        public void get(String data) {
                            mData = data;
                            mActivityTvLeverage.setText(mData + "x");
                        }
                    });
                    leverSetCounterDialog.show();
                }
            });

        }

    }

    @Override
    public void setData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    public void setButState() {
        mActivityCounterButZhang.setSelected(false);
        mActivityCounterButType.setSelected(false);
    }

    public void setButType() {
        mActivityCounterButLong.setSelected(false);
        mActivityCounterButShort.setSelected(false);
    }


    private void getMxCcontracts(String type) {
        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
        RequestParams params = new RequestParams();
        params.addHeader("app-version", Config.VERSION);
        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
        params.addHeader("my-client", "android");
        params.addQueryStringParameter("contract_id", type);

        int num = (int) ((Math.random() * 9 + 1) * 100000);
        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Log.i("mgfubvjsjhdjshdsjhdygu", responseInfo.result);

                try {

                    JSONObject jsonObj = new JSONObject(responseInfo.result);
                    if (jsonObj.getString("code").equals("1")) {

                        Gson gson = new Gson();
                        FuturesInfo futuresInfo = gson.fromJson(responseInfo.result, FuturesInfo.class);
                        setInfo(futuresInfo);
                        String leverage_steps = futuresInfo.getData().getLeverage_steps();
                        mIsreverse = futuresInfo.getData().getAllow_cross();
                        if ("1".equals(mIsreverse)) {
                            mFragmentLinType.setVisibility(View.VISIBLE);
                            mFragmentQiangpingYuE.setVisibility(View.VISIBLE);
                            mFragmentQiangpingNumber.setVisibility(View.VISIBLE);
                        } else {
                            mFragmentLinType.setVisibility(View.GONE);
                            mFragmentQiangpingYuE.setVisibility(View.GONE);
                            mFragmentQiangpingNumber.setVisibility(View.GONE);
                        }
                        Log.i("wleijfwoijefwe", mIsreverse);
                        String[] split = leverage_steps.split(",");
                        mStrings = new ArrayList<>();
                        for (int i = 0; i < split.length; i++) {
                            mStrings.add(split[i]);
                        }
                        if (mStrings != null) {
                            if (mStrings.size() > 4) {
                                mData = mStrings.get(3);
                                mActivityTvLeverage.setText(mStrings.get(3) + "x");
                                max = mStrings.get(mStrings.size() - 1);
                                Log.i("wlefjwljif", max);
                            }

                        }

                    } else {

                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }

        });

    }

    private void setInfo(FuturesInfo futuresInfo) {
        String contract_anchor = futuresInfo.getData().getContract_anchor();
        mQuote_anchor = futuresInfo.getData().getQuote_anchor();
        String settle_anchor = futuresInfo.getData().getSettle_anchor();
        mPrice_float_num = futuresInfo.getData().getPrice_float_num();
        mFragmentQiangpingOpenPrice.setText(mQuote_anchor);
        mFragmentQiangpingOpenNumber.setText(mQuote_anchor);
        mFragmentQiangpingOpenYuE.setText(settle_anchor);

    }

    //    分仓计算
    public void geQiangpingPricetValue() {
        //强平价=开仓价*（1+mm）/（1+L)
        mActivityCounterLinShouyi.setVisibility(View.VISIBLE);

        if (mIsreverse.equals("1")) {


            if (type.equals("1")) {
                String QiangpingPrice = mEditTextQiangpingPrice.getText().toString().trim();

                if (!TextUtils.isEmpty(max)) {
                    double mm = (1 / Double.valueOf(max)) * 0.5;
                    Double Pricee = Double.valueOf(QiangpingPrice);
                    //Pricee=  开仓价  mData=杠杆
                    //double v = (Pricee * (1 + mm)) / (1 + 1 / Double.valueOf(mData)) + mm;
                    double v = (Pricee * (1 + mm)) / (1 + 1 / Double.valueOf(mData));
                    String trim = Tools.round(v, Integer.valueOf(mPrice_float_num)).toString().trim();
                    Log.i("wejfkwjefiw", mData + "=============" + max + "===================" + String.valueOf(Pricee) + "==============" + mm);
                    mFragmentTvQiangpingPrice.setText(trim);
                }
            } else {
                String QiangpingPrice = mEditTextQiangpingPrice.getText().toString().trim();

                if (!TextUtils.isEmpty(max)) {
                    double mm = (1 / Double.valueOf(max)) * 0.5;
                    Double Pricee = Double.valueOf(QiangpingPrice);
                    // Pricee=  开仓价  mData=杠杆
                    double v = (Pricee * (1 - mm)) / (1 - 1 / Double.valueOf(mData));
                    String trim = Tools.round(v, Integer.valueOf(mPrice_float_num)).toString().trim();
                    Log.i("wejfkwjefiw", mData + "=============" + max + "===================" + String.valueOf(Pricee) + "==============" + mm);
                    mFragmentTvQiangpingPrice.setText(trim);
                }
            }
        } else {

            //          正向
            if (type.equals("1")) {
//               强平价= 开仓价*（L-1)/(L*(1-mm））
                Log.i("dwoejowijefowf", "1");

                Double price = Double.valueOf(mEditTextQiangpingPrice.getText().toString().trim());
                double mm = (1 / Double.valueOf(max)) * 0.5;
                double v = (price * (Double.valueOf(mData) - 1) / (Double.valueOf(mData) * (1 - mm)));
                mFragmentTvQiangpingPrice.setText(Tools.round(v, Integer.valueOf(mPrice_float_num)).toString().trim());


            } else {
                Log.i("dwoejowijefowf", "2");
                Double price = Double.valueOf(mEditTextQiangpingPrice.getText().toString().trim());
                double mm = (1 / Double.valueOf(max)) * 0.5;
                double v = (price * (Double.valueOf(mData) + 1) / (Double.valueOf(mData) * (1 + mm)));
                mFragmentTvQiangpingPrice.setText(Tools.round(v, Integer.valueOf(mPrice_float_num)).toString().trim());

            }

        }


    }

    //计算全仓
    public void getQuanCangValue() {

        mActivityCounterLinShouyi.setVisibility(View.VISIBLE);
        String Price = mEditTextQiangpingPrice.getText().toString().trim();
        String number = mEditTextQiangpingcang.getText().toString().trim();
        String yu_e = mEditTextQiangpingNumber.getText().toString().trim();

        if (mIsreverse.equals("1")) {

            if (isZhang) {
                if (type.equals("1")) {
//              反向做多
                    double mm = (1 / Double.valueOf(max)) * 0.5;
                    double shang = 1 + mm;
                    double v = Double.valueOf(yu_e) / Double.valueOf(number);
                    double v1 = 1 / Double.valueOf(Price);
                    double xia = v + v1;
                    double doublevalue = shang / xia;

                    Log.i("wijdowiefowifh", String.valueOf(doublevalue));
                    mFragmentTvQiangpingPrice.setText(Tools.round(doublevalue, Integer.valueOf(mPrice_float_num)).toString().trim());


                } else {
//              反向做空
                    double mm = (1 / Double.valueOf(max)) * 0.5;
                    double shang = 1 - mm;
                    double v = Double.valueOf(yu_e) / Double.valueOf(number);
                    double v1 = 1 / Double.valueOf(Price);
                    double xia = v - v1;
                    double doublevalue = shang / xia;
                    Log.i("wijdowiefowifh", String.valueOf(doublevalue));
                    mFragmentTvQiangpingPrice.setText("-" + Tools.round(doublevalue, Integer.valueOf(mPrice_float_num)).toString().trim());

                }
            } else {

                Log.i("kwecfwuehiuwheivhwe", "111111");
                if (type.equals("1")) {
//              反向做多
                    double mm = (1 / Double.valueOf(max)) * 0.5;
                    double shang = 1 + mm;
                    double v2 = Double.valueOf(Price) * Double.valueOf(number);
//                    double v = Double.valueOf(yu_e) / Double.valueOf(number);
                    double v = Double.valueOf(yu_e) / v2;
                    double v1 = 1 / Double.valueOf(Price);
                    double xia = v + v1;
                    double doublevalue = shang / xia;

                    Log.i("wijdowiefowifh", String.valueOf(doublevalue));
                    mFragmentTvQiangpingPrice.setText(Tools.round(doublevalue, Integer.valueOf(mPrice_float_num)).toString().trim());


                } else {
//              反向做空
                    double mm = (1 / Double.valueOf(max)) * 0.5;
                    double shang = 1 - mm;
                    double v2 = Double.valueOf(Price) * Double.valueOf(number);
//                    double v = Double.valueOf(yu_e) / Double.valueOf(number);
                    double v = Double.valueOf(yu_e) / Double.valueOf(v2);
                    double v1 = 1 / Double.valueOf(Price);
                    double xia = v - v1;
                    double doublevalue = shang / xia;
                    Log.i("wijdowiefowifh", String.valueOf(doublevalue));
                    mFragmentTvQiangpingPrice.setText("-" + Tools.round(doublevalue, Integer.valueOf(mPrice_float_num)).toString().trim());

                }
            }


        } else {


        }


    }

    public void setState() {
        mActivityCounterButShouyilv.setSelected(false);
        mActivityCounterButShouyi.setSelected(false);
    }


}
